<?php
namespace app\models;

use Yii;
use yii\base\Model;
use app\models\Basic;
use yii\web\UploadedFile;
use common\models\UploadForm;
use common\component\tool\Tool;


class Tplinfo extends Basic
{
	public static function tableName()
    {
        return '{{%tplinfo}}';
    }

	public function rules()
    {
        return [
            ['app_id', 'default', 'value' => 0],
            ['app_id', 'integer', 'message' => 'app_id必须为数字，或数字字符串', 
                        'min'=>0, 'tooSmall' => 'app_id最小存储0', 
                        'max'=>4294967295, 'tooBig' => 'app_id最大存储4294967295'],
            ['tplname', 'required', 'message' => 'tplname不能为空', 'on' => 'add'],
            ['tplname', 'string', 'message' => 'tplname必须是字符串',
                           'max' => 16, 'tooLong' => 'tplname最长16位'],
            /*注释原因：不需要在这里设置语言了*/
            // ['lang', 'string', 'message' => 'lang必须是字符串',
            //                'max' => 8, 'tooLong' => 'lang最长8位'],
            ['preview', 'string', 'message' => 'preview必须是字符串',
                           'max' => 256, 'tooLong' => 'preview最长256位'],
            ['updataflag', 'integer', 'message' => 'updataflag必须为数字，或数字字符串'],
            ['updataflag', 'in', 'range' => array(1, 2), 'message' => 'updataflag值必须在1,2中选择'],
            ['tplfolder', 'string', 'message' => 'tplfolder必须是字符串',
                           'max' => 32, 'tooLong' => 'tplfolder最长32位'],
            ['folder', 'string', 'message' => 'folder必须是字符串',
                           'max' => 128, 'tooLong' => 'folder最长128位'],
            ['gitadd', 'string', 'message' => 'gitadd必须是字符串',
                           'max' => 256, 'tooLong' => 'gitadd最长256位'],
            ['tplcate', 'integer', 'message' => 'tplcate必须为数字，或数字字符串'],
            ['tplcate', 'in', 'range' => array(1, 2), 'message' => 'tplcate值必须在1,2中选择'],
            ['isdefault', 'integer', 'message' => 'isdefault必须为数字，或数字字符串'],
            ['isdefault', 'in', 'range' => array(1, 2), 'message' => 'isdefault值必须在1,2中选择'],
            ['systpl', 'integer', 'message' => 'systpl必须为数字，或数字字符串'],
            ['systpl', 'in', 'range' => array(1, 2), 'message' => 'systpl值必须在1,2中选择'],
            ['add_time', 'default', 'value' => '1000-01-01 00:00:00'],
            ['add_time', 'date', 'format'=>'yyyy-MM-dd HH:mm:ss', 'message' => 'add_time非yyyy-MM-dd HH:mm:ss格式'],
        ];
    }


    /*
    上传模板压缩包
    $uploadFileName      文件夹名称（就是appid）
    $app_id     实例(对内)
    */
    public function upload($uploadFileName, $app_id = 0, $id = 0)
    {
        /*上传过来的图片，放到指定的位置*/
        $UploadForm = new UploadForm();
        $UploadForm->file = UploadedFile::getInstance($UploadForm, 'file');
        // P($UploadForm->file);
        if ($UploadForm->file && $UploadForm->validate()) {
            if($id == 0){
                $fileName = date("YmdHis").Tool::generateRandomStr(3, 'num');//文件名称
            }else{
                $tplinfo = self::find()->where('id = :id', [':id' => $id])->one();
                if(!empty($tplinfo)){
                    $fileName = $tplinfo->tplfolder;
                }else{
                    $fileName = 'none'.Tool::generateRandomStr(3, 'num');//文件名称
                }
            }
            $fileSuffix = '.' . $UploadForm->file->extension;//文件后缀
            /*判断图片类型是否在允许的范围内，主要判断type*/
            // P($UploadForm->file->type);
            if($UploadForm->file->type != 'application/x-zip-compressed'){
                P('此类型不允许上传');
            }
            if($fileSuffix == '.'){
                $fileSuffix = '.zip';
                // P($fileSuffix);
            }
            $folderName = date('Ymd');//放进今天日期的文件夹中
            $path = Yii::$app->basePath . '/web/templates/' . $uploadFileName;//存放的路径(原始文件)（不包含文件名）
            if(!file_exists($path)){//创建今天日期的文件夹
                mkdir($path, 0777, true);
                chmod($path, 0777);
            }
            $filepath = $path . '/' . $fileName . $fileSuffix;//文件路径(包括文件名)
            $zippath = $path . '/' . $fileName . '/';//解压路径
            if($UploadForm->file->saveAs($filepath)){
                /*解压zip*/
                if(file_exists($filepath)){
                    $zip = new \ZipArchive;
                    $pass = false;
                    if ($zip->open($filepath) === true) {
                        $zip->extractTo($zippath);
                        $zip->close();
                        $pass = true;
                    }
                    unlink($filepath);
                    if($pass){
                        return $fileName;
                    }
                }
            }
            return false;
        }
    }


    /*添加*/
    public function addTplinfo($data, $app_id)
    {
        // P($data);
        $this->scenario = 'add';
        $data['Tplinfo']['app_id'] = $app_id;
        if(isset($data['Tplinfo']['preview']) and is_array($data['Tplinfo']['preview'])){
            $data['Tplinfo']['preview'] = Tool::changeUploadFormat($data['Tplinfo']['preview']);
        }
        if(isset($data['Tplinfo']['isdefault'])){
            $data['Tplinfo']['isdefault'] = Tool::changeBool($data['Tplinfo']['isdefault']);
        }
        if($this->userInfo['comid'] == '00000000'){//超级管理添加的模板，默认为系统模板
            $data['Tplinfo']['systpl'] = 2;
        }
        $data['Tplinfo']['add_time'] = date('Y-m-d H:i:s', time());
        // P($data);
        if($this->load($data) and $this->validate()){
            // P($this);
            if($this->save(false)){
                $id = $this->getPrimaryKey();
                return $id;
                // return true;
            }
        }
        return false;
    }

    /*修改*/
    public function modifyTplinfo($data, $id, $appid)
    {
        // P($data);
        $tplinfo = self::find()->where('id = :id', [':id' => $id])->one();
        /*判断是否已经克隆过仓库，即判断是否创建了仓库文件，如果创建了，说明已经克隆了，就不能更改gitadd参数*/
        $path = Yii::$app->basePath . '/' . Yii::$app->params['templates'] . '/' . $appid . '/' . $tplinfo->id;
        if(!file_exists($path)){//不存在
            $clone = false;
        }else{//存在
            $clone = true;
        }
        // P($clone);
        if(isset($data['Tplinfo']['preview']) and is_array($data['Tplinfo']['preview'])){
            $data['Tplinfo']['preview'] = Tool::changeUploadFormat($data['Tplinfo']['preview']);
        }
        if(isset($data['Tplinfo']['isdefault'])){
            $data['Tplinfo']['isdefault'] = Tool::changeBool($data['Tplinfo']['isdefault']);
        }
        // P($data);
        if(!is_null($tplinfo)){
            if($this->load($data) and $this->validate()){
                if(isset($this->tplname)){
                    $tplinfo->tplname = $this->tplname;
                }
                /*注释原因：不需要在这里设置语言了*/
                // if(isset($this->lang)){
                //     $tplinfo->lang = $this->lang;
                // }
                if(isset($this->preview)){
                    $tplinfo->preview = $this->preview;
                }
                if(isset($this->folder)){
                    $tplinfo->folder = $this->folder;
                }
                if(!$clone){
                    if(isset($this->gitadd)){
                        $tplinfo->gitadd = $this->gitadd;
                    }
                }
                if(isset($this->isdefault)){
                    $tplinfo->isdefault = $this->isdefault;
                }
                if($tplinfo->save(false)){
                    return true;
                }
            }
        };
        return false;
    }

}
?>